/**
 * 2010(c) Copyright Oceansoft Information System Co.,LTD. All rights reserved.
 * <p>
 * Compile: JDK 1.6+
 * <p>
 * 版权所有(C)：江苏欧索软件有限公司
 * <p>
 * 公司名称：江苏欧索软件有限公司
 * <p>
 * 公司地址：中国苏州科技城青山路1号
 * <p>
 * 网址: http://www.oceansoft.com.cn
 * <p>
 * 作者: 090922(陈伟)
 * <p>
 * 文件名: com.oceansoft.mobile.econsole.modules.member.service.impl.MemberServiceImpl.java
 * <p>
 * 类产生时间: 2014-6-16 0016 下午 15:46
 * <p>
 * 负责人: 090922(陈伟)
 * <p>
 * Email:javacspring@gmail.com
 * <p>
 * 所在组 : 掌上公安应用平台
 * <p>
 * 所在部门: 开发部--手持技术部
 * <p>
 * <p>
 */
package com.oceansoft.mobile.econsole.modules.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.oceansoft.mobile.econsole.cache.redis.CacheBaseService;
import com.oceansoft.mobile.econsole.common.constant.Constant;
import com.oceansoft.mobile.econsole.common.util.HttpClientUtil;
import com.oceansoft.mobile.econsole.common.util.MD5Util;
import com.oceansoft.mobile.econsole.common.util.StringUtils;
import com.oceansoft.mobile.econsole.common.util.encrypt.Des3;
import com.oceansoft.mobile.econsole.common.util.encrypt.DesAPPUtils;
import com.oceansoft.mobile.econsole.common.util.encrypt.Md5;
import com.oceansoft.mobile.econsole.common.util.web.PageUtil;
import com.oceansoft.mobile.econsole.modules.api.entity.Monitor;
import com.oceansoft.mobile.econsole.modules.api.persistence.IDriverInfoApiMapper;
import com.oceansoft.mobile.econsole.modules.api.persistence.IRoadMapper;
import com.oceansoft.mobile.econsole.modules.api.service.IQueryService;
import com.oceansoft.mobile.econsole.modules.api.service.ISmsService;
import com.oceansoft.mobile.econsole.modules.base.entity.Pager;
import com.oceansoft.mobile.econsole.modules.base.entity.Query;
import com.oceansoft.mobile.econsole.modules.base.entity.Result;
import com.oceansoft.mobile.econsole.modules.member.entity.Line;
import com.oceansoft.mobile.econsole.modules.member.entity.Member;
import com.oceansoft.mobile.econsole.modules.member.entity.WtMember;
import com.oceansoft.mobile.econsole.modules.member.persistence.IMemberMapper;
import com.oceansoft.mobile.econsole.modules.member.persistence.IWtMemberMapper;
import com.oceansoft.mobile.econsole.modules.member.service.IMemberService;
import com.oceansoft.mobile.econsole.modules.member.service.IWtMemberService;
import com.oceansoft.mobile.econsole.modules.pay.StringUtil;
import com.oceansoft.mobile.econsole.webservice.idinspection.Constants;
import com.oceansoft.mobile.econsole.webservice.idinspection.SZRkkAuthService;
import com.oceansoft.mobile.econsole.webservice.idinspection.SZRkkAuthServiceService;
import com.oceansoft.mobile.econsole.weixin.util.StrUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

import javax.annotation.Resource;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * 注册客户端管理业务组件实现类
 *
 * @author: chenw
 * @time: 2014-6-16 0016 下午 15:46
 */
@Service
@Transactional
public class MemberServiceImpl extends CacheBaseService implements IMemberService {

    private static final int SYNC_CODE_USER_NO_EXISTS = -1;//当前登录用户不存在
    private static final int SYNC_CODE_GET_PWD_FAILURE = 1;//获取网厅密码失败
    private static final int SYNC_CODE_DATA_SYNC_SUCC = 2;//密码匹配成功
    private static final int SYNC_CODE_PWD_MATCH_FAILURE = 3; //密码不与网厅不匹配
    private static final int SYNC_CODE_NO_REQUIRED = 4; //无须同步

    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(Member.class);

    @Resource
    private IMemberMapper memberMapper;

    @Resource
    private IWtMemberService wtMemberService;

    @Resource
    private IDriverInfoApiMapper driverInfoApiMapper;

    @Resource
    private ISmsService smsService;

    @Resource
    private IRoadMapper roadMapper;

    @Resource
    private IQueryService queryService;

    @Resource
    private IWtMemberMapper wtMemberMapper;

    private static JSONObject parseXML(String response) throws IOException, SAXException, ParserConfigurationException {
        final JSONObject result = new JSONObject(2);
        final String TAG_NODE_STATUS = "姓名";
        final String TAG_NODE_BODY = "BODY";
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        parser.parse(new ByteArrayInputStream(response.getBytes("UTF-8")), new DefaultHandler() {
            String parentNode;
            JSONObject temp;
            String currText;

            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
                if (TAG_NODE_STATUS.equalsIgnoreCase(qName) || TAG_NODE_BODY.equalsIgnoreCase(qName)) {
                    temp = new JSONObject();
                    parentNode = qName;
                }
            }

            @Override
            public void characters(char[] ch, int start, int length) throws SAXException {
                currText = new String(ch, start, length);
            }

            @Override
            public void endElement(String uri, String localName, String qName) throws SAXException {
                if (TAG_NODE_STATUS.equalsIgnoreCase(qName)) {
                    result.put("姓名", currText);
                    temp = null;
                } else if (TAG_NODE_BODY.equalsIgnoreCase(qName)) {
                    result.put("body", currText);
                    temp = null;
                } else {
                    if (null != temp) {
                        temp.put(qName, currText);
                        currText = null;
                    }
                }
            }

            @Override
            public void error(SAXParseException e) throws SAXException {
                System.out.println("响应结果SAX解析错误！");
            }

            @Override
            public void endDocument() throws SAXException {
                temp = null;
                parentNode = null;
                currText = null;
            }
        });
        return result;
    }

    /**
     * 更新本地用户并更新网厅用户
     *
     * @param member 登录用户信息
     * @return Result
     */
    @Override
    public Result updateWtMember(final Member member) {
        WtMember wtMember = new WtMember();
        wtMember.setUserName(member.getMobile());
        wtMember.setPassword("");
        String identifyStatus = member.getCertificate();
        try {
            wtMember.setMobile(DesAPPUtils.encrypt(member.getMobile()));
            // 台胞证、身份证、组织机构代码、护照都用 usercode，需加一下判断
            //idCard 个人身份证号不能为空
            wtMember.setUserType(String.valueOf(Member.MEMBER_TYPE_GR));
            // 判断用户身份证是否通过实名认证，未认证通过
            if ("0".equals(member.getCertificate()) || "-9".equals(member.getCertificate())) {
                if (member.getIdCard() != null && member.getIdCard().indexOf("********") == -1) {
                    wtMember.setUserCode(DesAPPUtils.encrypt(member.getIdCard()));//身份证号
                    // 增加实名认证 BY shaom
                    queryService.queryIdNumCheck(member.getGuid(), member.getRealName(), member.getIdCard());
                    //实名认证中
                    identifyStatus = "2";
                    wtMember.setCsny(new Date());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Result.FAILURE, "加密出错");
        }

        wtMember.setAliasName(member.getRealName());//真实姓名
        wtMember.setGuid(member.getGuid());
        wtMember.setAddress(member.getAddress());
        if (member.getAddress() != null && !"".equals(member.getAddress())) {
            String[] address = member.getAddress().split("-");
            if (address.length == 4) {
                wtMember.setProvince(address[0]);
                wtMember.setCity(address[1]);
                wtMember.setArea(address[2]);
                wtMember.setStreet(address[3]);
            } else if (address.length == 3) {
                wtMember.setProvince(address[0]);
                wtMember.setCity(address[1]);
                wtMember.setArea(address[2]);
                wtMember.setStreet("");
            }
        }

        wtMember.setLinkName(member.getContacts());
        wtMember.setEmail(member.getEmail());
        // 保存用户信息至网厅用户信息表
        Result result = wtMemberService.updateWtMemberInfo(wtMember);
        if (result.isSucc()) {
            wtMember.setIdentifystatus(identifyStatus);
            result.setData(wtMember);//实名认证返回
            return result;
        } else {
            return new Result(Result.FAILURE, "更新失败:" + result.getMsg());
        }

    }

    public Boolean resetWtPassword(final String userName, final String pwd) {
        WtMember wtMember = new WtMember();
        //wtMember.setGuid(userguid);
        wtMember.setUserName(userName);
        wtMember.setPassword(pwd);
        //Result result = wtMemberService.updateWtMemberPwd(wtMember);
        Result result = wtMemberService.updateWtMemberPwdByUserName(wtMember);
        return result.isSucc();

    }

    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public Result resetPassword(String id, String telNum, String pwd, String validateCode, String originPwd) {
        //检验验证码是否正确  pwd 加密后的密码  originPwd 明文密码
        String cacheCode = smsService.getValidateCode(Constant.SMS_BIZ_RESET_PASSWORD, telNum);
        if (!org.springframework.util.StringUtils.hasText(cacheCode)) {
            return new Result(Result.FAILURE, "验证码已失效，请重新获取");
        }
        if (!cacheCode.equals(validateCode)) {
            return new Result(Result.FAILURE, "输入的验证码不正确");
        }

        int count = memberMapper.loadUserByTel(telNum);
        if (count == 0) {
            return new Result(Result.FAILURE, "当前用户未注册");
        }

        //resetWtPassword(member.getGuid(), originPwd);
        boolean flag = resetWtPassword(telNum, pwd);
        if (flag) {
            smsService.clearValidateCode(Constant.SMS_BIZ_RESET_PASSWORD, telNum);
            //重置缓存用户密码，用户表存在相同username的记录。根据username不能唯一定位到用户
            /*member.setPassword(pwd);
            super.set(MD5Util.getMD5String(member.getLoginId()), JSON.toJSONString(member));*/
            super.delCache(MD5Util.getMD5String(telNum));
            return new Result(Result.SUCC, "密码重置成功");
        } else {
            return new Result(Result.FAILURE, "密码重置失败");
        }

    }

    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public Result rebindUserMobile(int bizType, String idcard, String oldTel, String newTel, String newCode) {
        WtMember wtMember = null;
        try {
            wtMember = wtMemberMapper.loadUserByIdcardAndTel(DesAPPUtils.encrypt(idcard), oldTel);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Result.FAILURE, "身份证加密失败");
        }
        if (null == wtMember) {
            return new Result(Result.FAILURE, "身份证或手机号码不正确");
        }
        int count = memberMapper.loadUserByTel(newTel);
        if (count > 0) {
            return new Result(Result.FAILURE, "新绑定的手机号已注册");
        }

        String newCacheKey = smsService.getValidateCode(bizType, newTel);
        if (!org.springframework.util.StringUtils.hasText(newCacheKey)) {
            return new Result(Result.FAILURE, "新手机号验证码已失效，请重新获取");
        }
        // 验证码正确
        if (newCacheKey.equals(newCode)) {
            // 只更新用户名、手机号两个字段
            WtMember wt = new WtMember();
            wt.setGuid(wtMember.getGuid());
            // 修改用户名为新手机号
            wt.setUserName(newTel);
            try {
                // 加密手机号
                wt.setMobile(DesAPPUtils.encrypt(newTel));
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(Result.FAILURE, "加密出错");
            }
            Result result = wtMemberService.updateWtMemberMobile(wt);
            if (result.isSucc()) {
                // 清空redis中原用户信息
                super.delCache(MD5Util.getMD5String(wtMember.getUserName()));
                // 清空验证码
                smsService.clearValidateCode(bizType, newTel);
                return new Result(Result.SUCC, newTel, "手机绑定成功");
            } else {
                return new Result(Result.FAILURE, null, "手机绑定失败");
            }
        }

        if (!newCacheKey.equals(newCode)) {
            return new Result(Result.FAILURE, null, "新手机号验证码错误");
        }
        return new Result(Result.FAILURE, null, "异常");
    }


    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public Result userLoginAuthentication(Member loginUser) throws Exception {
        if (StringUtils.isEmpty(loginUser.getLoginId()) || StringUtils.isEmpty(loginUser.getPassword())) {
            return new Result(Result.FAILURE, "用户名或密码错误");
        }
        //1.从Redis中检索，命中则直接进行检验，否则传统方式检验
        // 在PC端修改完密码，此用户在手机端登录失败。因为redis未更新成新的
        WtMember wtMember = wtMemberMapper.getInfoByUserName(loginUser.getLoginId());
        if (wtMember == null) {
            return new Result(Result.FAILURE, "用户不存在");
        } else {
            if (!wtMember.getPassword().equals(MD5Util.getMD5String(loginUser.getPassword()))) {
                return new Result(Result.FAILURE, "用户名或密码错误");
            } else if (wtMember.getPassword().equals(MD5Util.getMD5String(loginUser.getPassword()))) {
                return authenticationProcess(wtMember);
            } else {
                return new Result(Result.FAILURE, "用户名或密码错误");
            }
        }
    }

    /**
     * 登录用户认证信息处理
     *
     * @param _user
     * @return
     */
    private Result authenticationProcess(WtMember _user) {
        if (_user != null) {
            switch (_user.getUseable()) {
                case Member.MEMBER_STATUS_LOCK:
                    return new Result(Result.FAILURE, "当前用户被锁定");
                case Member.MEMBER_STATUS_NORMAL:
                    //_user.setLoginTime(new Date());
                    //更新用户登录时间
                    String loginId = _user.getUserName();
                    Date loginTime = new Date();
                    memberMapper.insertLogin(loginId, loginTime);
                    _user.setPassword("");
                    // 增加实名认证结果给APP
                    _user.setIdentifystatus(rz(_user.getGuid()));
                    /*WtMember wtMember= wtMemberMapper.getWtMemberByUserGuid(_user.getGuid());
                    // 上次进行实名认证的时间  APP端不需要
                    _user.setCsny(wtMember.getCsny()); */
                    if (StringUtil.isNotBlank(_user.getUserCode())) {
                        try {
                            _user.setUserCode(DesAPPUtils.decrypt(_user.getUserCode()));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    return new Result(_user);
                case Member.MEMBER_STATUS_DISABLE:
                    return new Result(Result.FAILURE, "当前用户已被禁用");
                default:
                    return new Result(Result.FAILURE, "用户状态错误");
            }
        } else {
            return new Result(Result.FAILURE, "用户名或密码错误");
        }
    }

    @Deprecated
    @Override
    public Result authentication(Member user) throws IOException {
        WtMember loginUser = wtMemberMapper.getInfoByUserName(user.getLoginId());

        if (loginUser != null) {
            switch (loginUser.getUseable()) {
                case Member.MEMBER_STATUS_LOCK:
                    return new Result(Result.FAILURE, "用户被锁定");
                case Member.MEMBER_STATUS_NORMAL:
                    //更新用户登录时间
//                	  _user.setLoginTime(new Date());
//
//                  	memberMapper.insertLogin(_user);
                    return new Result(loginUser);
                case Member.MEMBER_STATUS_DISABLE:
                    return new Result(Result.FAILURE, "用户已禁用");
                default:
                    return new Result(Result.FAILURE, "用户名或密码错误");
            }
        } else {
            return new Result(Result.FAILURE, "用户名或密码错误");
        }
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public Result register(final Member member) {
        // 获取验证码
        String _code = smsService.getValidateCode(Constant.SMS_BIZ_REGISTER, member.getMobile());
        Date regTime = new Date();
        // 手机号码
        String mobile = member.getMobile();
        // 姓名
        String realName = member.getRealName();
        // 身份证号
        String idCard = member.getIdCard();
        if (!org.springframework.util.StringUtils.hasText(_code)) {
            memberMapper.insertRegisterError(mobile, idCard, realName, regTime);
            return new Result(Result.FAILURE, "验证码已失效，请重新获取");
        }
        if (!_code.equals(member.getValidateCode())) {
            memberMapper.insertRegisterError(mobile, idCard, realName, regTime);
            return new Result(Result.FAILURE, "验证码错误");
        }
        int count = memberMapper.loadUserByTel(member.getMobile());
        if (count > 0) {
            memberMapper.insertRegisterError(mobile, idCard, realName, regTime);
            return new Result(Result.FAILURE, "该手机号码已注册");
        }
        // 保存用户信息
        WtMember wtMember = new WtMember();
        // 注册来源 P：大厅；W：微信；I：苹果；A：安卓
        wtMember.setZzmm(String.valueOf(member.getUserSrc()));
        wtMember.setUserName(member.getMobile());

        try {
            // 密码
            wtMember.setPassword(MD5Util.getMD5String(member.getPassword()));
            // 手机号
            wtMember.setMobile(DesAPPUtils.encrypt(member.getMobile()));
            // 用户类型，默认个人
            wtMember.setUserType(String.valueOf(Member.MEMBER_TYPE_GR));
            // 身份证号
            if (StringUtils.isNotBlank(member.getIdCard())) {
                wtMember.setUserCode(DesAPPUtils.encrypt(member.getIdCard()));
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Result.FAILURE, "加密出错，请重新注册");
        }

        wtMember.setAliasName(member.getRealName());
        wtMember.setGuid(UUID.randomUUID().toString());
        wtMember.setDateCreated(new Date());
        wtMember.setWeixinid(member.getOpenId());

        Result result = wtMemberService.saveWtMemner(wtMember);

        if (result.isSucc()) {
            return new Result(Result.SUCC, wtMember);
        } else {
            return new Result(Result.FAILURE, "注册失败:" + result.getMsg());
        }

    }


    @Override
    public Result isIdins(final String idCard, final String name) {
        if (!idCard.startsWith(Constants.SUZHOU_IDCARD_START))   //非苏州地区不进行认证
            return new Result(Result.SUCC, "身份信息检验成功", "检验成功");
        /*
        //FIXME:此处因为人口库调用身份证检验需要绑定主机IP，目前暂时由172.16.1.219中转，后续放开此处代码，直接调用人口库服务进行检验
        String resultStr = HttpClientUtil.doPost("http://172.16.1.219/econsole/api/validate/id", new HashMap<String, String>() {{
            put("id", idCard);
            put("name", name);
        }}, "UTF-8");
        return JSONObject.parseObject(resultStr, Result.class);*/
        //正式环境放开此处方法调用 已绑定IP为172.16.1.218、219、220三台服务器
        return idInsHandle(idCard, name);
    }

    private Result idInsHandle(String idCard, String name) {
        try {
            Des3 des3 = new Des3(Constants.APP_KEY);
            String body = parseXML(sendIdIns(idCard, name).replaceAll("\n", "")).getString("body");
            body = des3.decodeStr(body);
            logger.debug("人口库服务调用返回结果======>" + body);
            String status = parseXML(body).getString("姓名");
            if (StringUtils.isNotEmpty(status)) {
                if (status.equalsIgnoreCase("true")) {
                    return new Result(Result.SUCC, "身份证信息检验成功");
                }
                return new Result(Result.FAILURE, "身份证信息不匹配");
            } else {
                return new Result(Result.FAILURE, "身份证信息不匹配");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Result.FAILURE, "请求出错，请稍后再试");
        }
//        return new Result(Result.SUCC);
    }

    public String sendIdIns(String idCard, String name) throws Exception {
        SZRkkAuthService service = new SZRkkAuthServiceService().getSZRkkAuthServicePort();
        String bodyXml = "<RENYUANS><RENYUAN SFZH='" + idCard + "'><姓名>" + name + "</姓名>></RENYUAN></RENYUANS>";
        Des3 des3 = new Des3(Constants.APP_KEY);
        String param = "<Request><Head><DeptID>GONGANJU</DeptID><SysInfo>公安局</SysInfo><APPID>" + Constants.APP_ID + "</APPID><RequestTime>" + Constants.getRequestTime() + "</RequestTime><HashSign>" + Md5.getMD5Info(bodyXml) + "</HashSign><Version>1</Version><Priority>1</Priority></Head><Body>" + des3.encodeStr(bodyXml) + "</Body></Request>";
        logger.debug("\n\n=========人口库服务调用参数=======>" + param);
        String rt = service.execute(param);
        logger.debug("\n\n=========人口库服务调用返回=======>" + rt);
        return rt;
    }

    /**
     * 同步网厅用户注册
     *
     * @param pwd    明文密码
     * @param member Member
     * @return Result
     */
    @Override
    public Result webSych(final String pwd, final Member member) {
        WtMember wtMember = new WtMember();
        wtMember.setUserName(member.getMobile());
        try {
            wtMember.setPassword(MD5Util.getMD5String(pwd));
            wtMember.setMobile(DesAPPUtils.encrypt(member.getMobile()));
            //台胞证、身份证、组织机构代码、护照都用 usercode，需加一下判断

            if (member.getUnit() == Member.MEMBER_TYPE_GR) {
                //idCard 个人身份证号不能为空
                wtMember.setUserType(String.valueOf(Member.MEMBER_TYPE_GR));
                wtMember.setUserCode(DesAPPUtils.encrypt(member.getIdCard()));

            } else if (member.getUnit() == Member.MEMBER_TYPE_QY) {
                //orgId corporate corporateIdCard 企业代码 法人 法人身份证号不能为空
                wtMember.setUserType(String.valueOf(Member.MEMBER_TYPE_QY));
                wtMember.setUserCode(DesAPPUtils.encrypt(member.getOrgId()));
                wtMember.setCorporate(member.getCorporate());
                wtMember.setCorporateIdCard(DesAPPUtils.encrypt(member.getCorporateIdCard()));
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Result.FAILURE, "加密出错");
        }
        wtMember.setAliasName(member.getRealName());
        wtMember.setGuid(member.getGuid());
        wtMember.setDateCreated(member.getRegTime());
        Result result = wtMemberService.saveWtMemner(wtMember);

        /*保存PASC_MEMBERS_MANGE表
        WtMemberMange wtMemberMange = new WtMemberMange();
        wtMemberMange.setGuid(member.getGuid());
        wtMemberMange.setIdentityStatus(0);
        wtMemberMange.setIsCheck(1);
        wtMemberMange.setIsEnabled(0);
        wtMemberService.saveWtMemberMange(wtMemberMange);*/

        if (result.isSucc()) {
            return new Result(Result.SUCC, "同步网厅注册成功");
        } else {
            return new Result(Result.FAILURE, "注册失败:" + result.getMsg());
        }
    }

    @Override
    public String isConfirm(String userGuid) {
        String s = memberMapper.isConfirm(userGuid);
        if (StringUtils.isBlank(s)) {
            s = "0";
        } else {
            if (!s.equals("1"))
                s = "0";
        }
        return s;

    }

    @Override
    public Result loadPathInfo(String pathId) {
        List<Monitor> list = roadMapper.loadCustomLineMonitors(pathId);
        if (list.size() > 0) {
            return new Result(Result.SUCC, list, "加载成功");
        }
        return new Result(Result.FAILURE, "暂无数据");
    }

    @Override
    public Result loadCustomLines(int userId) {
        List<Line> list = roadMapper.loadCustomerLines(userId);
        if (list.size() > 0) {
            return new Result(Result.SUCC, list, "加载成功");
        }
        return new Result(Result.FAILURE, "暂无数据");
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public Result removeLine(String lindId) {
        if (!org.springframework.util.StringUtils.hasText(lindId))
            return new Result(Result.FAILURE, "请选择要移除的线路");
        int rt = roadMapper.removeLine(lindId);
        if (rt > 0) {
            return new Result(Result.SUCC, "移除线路成功");
        }
        return new Result(Result.FAILURE, "线路不存在或移除失败");
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public Result saveLine(Line line) {
        if (line.getUserId() < 1)
            return new Result(Result.FAILURE, "用户编号不能为空");
        if (!org.springframework.util.StringUtils.hasText(line.getLineName()))
            return new Result(Result.FAILURE, "线路名称不能为空");
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        line.setLineId(uuid);
        roadMapper.saveLine(line);
        if (line.getId() > 0)
            return new Result(Result.SUCC, uuid, "保存自定义线路信息成功");
        return new Result(Result.FAILURE, "保存自定义线路失败");
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public Result saveMonitor(Monitor monitor) {
        if (!org.springframework.util.StringUtils.hasText(monitor.getLineId()))
            return new Result(Result.FAILURE, "线路编号为空");
        if (!org.springframework.util.StringUtils.hasText(monitor.getDevId()))
            return new Result(Result.FAILURE, "监控点编号不能为空");
        if (!org.springframework.util.StringUtils.hasText(monitor.getDevName()))
            return new Result(Result.FAILURE, "监控点名称不能为空");
        //判断当前监控点是否已经存在
        int count = roadMapper.getMonitorCount(monitor.getLineId(), monitor.getDevId());
        if (count > 0) {
            return new Result(Result.FAILURE, "当前监控点已收藏");
        }
        roadMapper.saveMonitor(monitor);
        if (monitor.getId() > 0)
            return new Result(Result.SUCC, Integer.valueOf(monitor.getId()), "监控点收藏成功");
        return new Result(Result.FAILURE, "监控点收藏失败");
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public Result delMonitor(int pk) {
        if (pk < 1)
            return new Result(Result.FAILURE, "请选择要移除的监控点");
        int rt = roadMapper.removeMonitor(pk);
        if (rt > 0)
            return new Result(Result.SUCC, "移除监控点成功");
        return new Result(Result.FAILURE, "监控点不存在或移除失败");
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public Result openIdLogin(Member member) throws IOException {
        if (org.apache.commons.lang.StringUtils.isBlank(member.getLoginId())
                || org.apache.commons.lang.StringUtils.isBlank(member.getPassword())
                || org.apache.commons.lang.StringUtils.isBlank(member.getOpenId())
                ) {
            return new Result(Result.FAILURE, "用户名/密码/openId为空");
        }
        // 登录实时验证，不从redis获取。大厅修改密码，导致手机端旧密码还能登录
        try {
            // 根据手机号获取用户信息
            WtMember wtMember = wtMemberMapper.getInfoByUserName(member.getLoginId());
            if (wtMember == null) {
                return new Result(Result.FAILURE, "用户不存在");
            } else {
                if (!wtMember.getPassword().equals(MD5Util.getMD5String(member.getPassword()))) {
                    return new Result(Result.FAILURE, "用户名或密码错误");
                }/*else if(wtMember.getWeixinid()!=null && !"20".equals(wtMember.getWeixinid())){
                    return new Result(Result.FAILURE, "当前微信号已绑定用户【"+wtMember.getUserName()+"】，请解绑后再用【"+member.getLoginId()+"】登录");
                }*/ else if (wtMember.getPassword().equals(MD5Util.getMD5String(member.getPassword()))) {
                    return wxAuthenticationProcess(wtMember, member.getOpenId());
                } else {
                    return new Result(Result.FAILURE, "用户名或密码错误");
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Result.FAILURE, "密码加密错误，请重新登录");
        }
    }

    @Override
    public Pager<Member> findByPage(Query query) {
        PageHelper.startPage(query.getPageNum(), query.getNumPerPage(), true);
        Page<Member> page = (Page<Member>) memberMapper.loadMemberListByCondition(query);
        return PageUtil.page2pager(page, query);
    }

    @Override
    @Deprecated
    public String rz(WtMember member) {

        String guid = member.getGuid();
        String aliasName = member.getAliasName();
        String userCode = member.getUserCode();
        if (StrUtil.hasBlank(guid, aliasName, userCode)) {
            return "0";//未认证
        }

        String url = configInfo.getServiceInterfaceAddress() + "/member/certification/" + guid;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("realName", aliasName);
        jsonObject.put("idNum", userCode);
        String res = HttpClientUtil.doPut(url, jsonObject);

        JSONObject object = JSON.parseObject(res);
        boolean succ = object.getBooleanValue("succ");
        String data = object.getString("data");

        if (succ && Objects.equals("212001", data)) {
            return "1";//认证通过
        }
        logger.info("+++++++++++++ 实名认证返回数据显示认证未过~~ +++++++++++++++++");
        return "-1";
    }

    /**
     * 方法有BUG
     *
     * @param member
     * @return
     * @throws IOException
     */
    @Override
    @Deprecated
    public String rzxx(WtMember member) throws IOException {
        String guid = member.getGuid();
        String aliasName = member.getAliasName();
        String userCode = member.getUserCode();
        if (!StrUtil.hasBlank(guid, aliasName, userCode)) {
            String url = configInfo.getServiceInterfaceAddress() + "/member/" + guid;
            String res = HttpClientUtil.doGet(url);
            Objects.requireNonNull(res, "获取实名认证接口失败");
            JSONObject object = JSON.parseObject(res);
            boolean succ = object.getBooleanValue("succ");
            if (succ) {
                JSONObject data = object.getJSONObject("data");
                Objects.requireNonNull(data, "实名认证接口获取的数据异常");
                // authStatus: 0-未发起，1-已发起， 9-重新发起， 2-已认证
                String authStatus = data.getString("authStatus");
                if (Objects.equals("2", aliasName)) {//已经认证，采取获取认证状态
                    JSONObject memberStatus = data.getJSONObject("memberStatus");
                    if (Objects.nonNull(memberStatus)) {
                        String identityStatus = memberStatus.getString("identityStatus");
                        return identityStatus;
                    }
                }
                return authStatus;
            }
        }
        return member.getIdentifystatus();


        /*
        * 0:未认证
        * 1：已认证
        * 2：认证中
        * -1：未通过认证
        * */
/*        if (null!=object.getJSONObject("data")) {
            if(null!=object.getJSONObject("data").getJSONObject("memberStatus")){
                if(null!=object.getJSONObject("data").getJSONObject("memberStatus").get("identityStatus")){
                    return object.getJSONObject("data").getJSONObject("memberStatus").get("identityStatus").toString();// return 1或者-1
                }else{
                      if("0".equals(object.getJSONObject("data").get("authStatus").toString())){
                          return "0";
                      }else  if("1".equals(object.getJSONObject("data").get("authStatus").toString()) || "9".equals(object.getJSONObject("data").get("authStatus").toString())){
                          return "2";
                      }else{
                          return "1";
                      }
                }
            }else{
                return "0";
            }
        }else{
            return "0";
        }*/
    }


    /**
     * 登录用户认证信息处理
     *
     * @param _user
     * @return
     */
    private Result wxAuthenticationProcess(WtMember _user, String openId) {
        if (_user != null) {
            switch (_user.getUseable()) {
                case Member.MEMBER_STATUS_LOCK:
                    return new Result(Result.FAILURE, "当前用户被锁定");
                case Member.MEMBER_STATUS_NORMAL:
                    //_user.setLoginTime(new Date());
                    _user.setWeixinid(openId);
                    //更新用户登录时间
                    String loginId = _user.getUserName();
                    Date loginTime = new Date();
                    memberMapper.insertLogin(loginId, loginTime);

                    wtMemberMapper.updateOpenidByUserName(_user.getUserName(), openId);

                    _user.setPassword("");
                    return new Result(Result.SUCC, _user, "登录成功");
                case Member.MEMBER_STATUS_DISABLE:
                    return new Result(Result.FAILURE, "当前用户已被禁用");
                default:
                    return new Result(Result.FAILURE, "用户状态错误");
            }
        } else {
            return new Result(Result.FAILURE, "用户名或密码错误");
        }


    }

    /**
     * code 只要前4位
     *
     * @param code
     * @return
     */
    @Override
    public String findCode(String code) {
        code = code.substring(0, 4);
        String codexx = wtMemberMapper.findCode(code);
        return codexx;
    }

    /**
     * 查询认证信息，0：未认证 1：通过认证 2：认证中 -9：认证不通过
     *
     * @param userGuid
     * @return
     */
    @Override
    public String rz(String userGuid) {
        // 实名认证结果
        String rzResult = memberMapper.isConfirm(userGuid);
        if (StringUtils.isBlank(rzResult)) {
            WtMember wtMember = wtMemberMapper.getWtMemberByUserGuid(userGuid);
            if (wtMember != null && wtMember.getCertificate() == "0") {
                return "2";
            } else {
                return "0";
            }
        } else {
            return rzResult;
        }
    }


}
